/*
 * Copyright (C) 2012  E-dance Studio Harbin Institute of Technology 
 * Project:campusmobile
 * Author: 初楷博
 * Create Date: 2012-5-30下午08:09:26
 */
package hit.edance.campusmobile.chat.activity;

import java.util.Date;
import java.util.List;

import hit.edance.campusmobile.chat.R;
import hit.edance.campusmobile.chat.adapter.ChattingAdapter;
import hit.edance.campusmobile.chat.database.DBChatHistoryHelper;
import hit.edance.campusmobile.chat.listener.MessageListenerEx;
import hit.edance.campusmobile.chat.model.ActivityKiller;
import hit.edance.campusmobile.chat.model.ChatEntity;
import hit.edance.campusmobile.chat.model.ChatItem;
import hit.edance.campusmobile.chat.model.ChatMessage;
import hit.edance.campusmobile.chat.model.MyChatManager;
import hit.edance.campusmobile.chat.util.ConstantUtil;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.XMPPException;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

/**   
 * 聊天界面
 * 
 * @Project campusmobile
 * @Package hit.edance.campusmobile.chat.activity
 * @Class ActivityChat
 * @Date 2012-5-30 下午08:09:26
 * @author 初楷博
 * @version 1.0
 * @since 1.0
 */
public class ActivityChat extends Activity {
	/**
	 * 界面listview实例
	 */
	private ListView list;
	/**
	 * 发送按钮
	 */
	private Button sendButton;
	/**
	 * 发送信息编辑框
	 */
	private EditText text;
	/**
	 * title bar上面的textview
	 */
	private TextView tvname; 
	/**
	 * 聊天历史list
	 */
	private List<ChatMessage> messages;
	/**
	 * 聊天list的adapter
	 */
	private ChattingAdapter chatHistoryAdapter;
	/**
	 * activity's handler
	 */
	private Handler myhandler = null;
	/**
	 * 将要发送的信息
	 */
	private String sendStr = null;
	/**
	 * 当前界面聊天封装实例
	 */
	private ChatEntity chatEntity;
	/**
	 * openfire 聊天 对象
	 */
	private Chat chat;
	/**
	 * 当前聊天对象的JID
	 */
	private String currentJabberId;
	
	/**
	 * 聊天记录数据库对象
	 */
	private static DBChatHistoryHelper db;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		ActivityKiller.addActivity(hashCode(), this);
		//设置无标题模式
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat_chatting);
		//设置标题样式
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.chat_chatting_title_bar);
		db = new DBChatHistoryHelper(this);
		myhandler = new Handler(){

			/* @see android.os.Handler#handleMessage(android.os.Message)
			 *handleMessage
			 */
			@Override
			public void handleMessage(android.os.Message msg) {
				
				super.handleMessage(msg);
				switch (msg.what) {
				//当前聊天界面收到消息
				case MessageListenerEx.CURRENT_CHAT: {
					String receive = msg.getData().getString("msg");
					messages.add(new ChatMessage(ChatMessage.MESSAGE_FROM, receive));
					myhandler.post(flushList);
				}
					break;
				default:
					break;
				}
			}
			
		};
		//初始化界面
		initActivity();
		
	}


	/**
	 * 初始化ActivityChat
	 */
	private void initActivity() {
		//设置聊天监听器中的handler
		MessageListenerEx.getInstance().setMyhandler(myhandler);
		
		list = (ListView) findViewById(R.id.chatting_history_lv);
		sendButton = (Button) findViewById(R.id.send_button);
		text = (EditText) findViewById(R.id.text_editor);
		tvname = (TextView)findViewById(R.id.chatting_contact_name);
		
		sendButton.setOnClickListener(l);
		
		setAdapterForThis();
	}
	
	
	/* @see android.app.Activity#onNewIntent(android.content.Intent)
	 *onNewIntent
	 */
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		//设置新的intent
		setIntent(intent);
		//设置adapter
		setAdapterForThis();
	}


	/**
	 * 设置聊天历史的adapter
	 */
	private void setAdapterForThis() {
		//TODO
		//设置当前聊天对话窗口
		MyChatManager.setCurrentChattingActivity(this);
		currentJabberId = getIntent().getStringExtra("jabberId");
		if((chatEntity = MyChatManager.getChatEntityByJID(currentJabberId)) == null){
			chatEntity = MyChatManager.addChatEntity(new ChatEntity(currentJabberId,getIntent().getStringExtra("nickname")));
			chatEntity.setChat(MyChatManager.getChatmanager().createChat(currentJabberId, null));
		}
		//设置当前title为用户昵称
		tvname.setText(chatEntity.getNickname());
		//初始化聊天历史
		messages = chatEntity.getChatlist();
		//得到聊天对象
		chat = chatEntity.getChat();
		chatHistoryAdapter = new ChattingAdapter(this,messages);
		list.setAdapter(chatHistoryAdapter);
		//将未读消息置空
		chatEntity.setUnreadMessageCount(0);
	}

	/**
	 * 发送消息
	 */
	private View.OnClickListener l = new OnClickListener(){

		public void onClick(View v) {
			if (v.getId() == sendButton.getId()) {
				String str = text.getText().toString();
				if (str != null 
						&& (sendStr = str.trim().replaceAll("\r", "").replaceAll("\t", "").replaceAll("\n", "")
								.replaceAll("\f", "")) != "") {
					try {
						chat.sendMessage(sendStr);
						db.insertChatHistoryItem(new ChatItem(ConstantUtil.JID,
								currentJabberId, ChatMessage.MESSAGE_TO,
								new Date(), sendStr));
						messages.add(new ChatMessage(ChatMessage.MESSAGE_TO,
								sendStr));
						myhandler.post(flushList);
						
					} catch (XMPPException e) {
						e.printStackTrace();
					}
				}
				text.setText("");
			} 
		}
	};
	
	
	/**
	 * 刷新聊天历史
	 */
	private Runnable flushList = new Runnable(){

		public void run() {
			chatHistoryAdapter.notifyDataSetChanged();
		}
		
	};
	/**
	 * @return the messages 当前窗口聊天历史记录
	 */
	public List<ChatMessage> getMessages() {
		return messages;
	}

	/**
	 * @param messages the messages to set
	 */
	public void setMessages(List<ChatMessage> messages) {
		this.messages = messages;
	}

	/**
	 * 判断ActivityChat是否为activity栈顶端的活动窗口
	 * @return true 是当前应用程序顶端的活动窗口<br/>
	 * false 不是...
	 */
	public boolean isIAmTop() {
		ActivityManager activityManager = (ActivityManager) getApplicationContext()
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> forGroundActivity = activityManager
				.getRunningTasks(1);
		RunningTaskInfo currentActivity;
		currentActivity = forGroundActivity.get(0);
		String activityName = currentActivity.topActivity.getClassName();
		if (activityName
				.equals("hit.edance.campusmobile.chat.activity.ActivityChat"))
			return true;
		else
			return false;

	}


	/* @see android.app.Activity#onStop()
	 *onStop
	 */
	@Override
	protected void onStop() {
		super.onStop();
		MyChatManager.setCurrentChattingActivity(null);
	}


	/**
	 * @return the currentJabberId
	 */
	public String getCurrentJabberId() {
		return currentJabberId;
	}


	/**
	 * @param currentJabberId the currentJabberId to set
	 */
	public void setCurrentJabberId(String currentJabberId) {
		this.currentJabberId = currentJabberId;
	}


	/**
	 * @return the db
	 */
	public static DBChatHistoryHelper getDb() {
		return db;
	}


	/* @see android.app.Activity#onDestroy()
	 *onDestroy
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		ActivityKiller.killActivityByHashCode(hashCode());
	}
	
}
